package com.apestech.api.query.sys.erp;

import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.condition.FieldSqlCallback;

public class ErpRoleSql implements FieldSqlCallback {

    private String postId;
    private String type;
    private String purpose;
    private JSONObject input;

    public ErpRoleSql(String postId, String type, String purpose) {
        this.postId = postId;
        this.type = type;
        this.purpose = purpose;
    }

    public void setInput(JSONObject input) {
        this.input = input;
    }

    @Override
    public String getFieldSql(String alias, String field, Table tab) throws Exception {
        String sTab="";
        String qxField=null;
        if("pp_search".equals(purpose)){
            sTab="QX_CX_"+type;
            if(input!=null){
                qxField=input.getString("F_CXQX");
            }
        } else {
            sTab="QX_CZ_"+type;
            if(input!=null){
                qxField=input.getString("F_CZQX");
            }
        }
        boolean flag=true;
        if(qxField!=null && (";"+qxField+";").indexOf(";"+field+";")<0 && (";"+qxField+";").indexOf("#"+field+";")<0){
            flag=false;
        }
        if(flag){
            String f=field;
            if(alias!=null && !"".equals(alias)) f=alias+"."+f;
            String sql=" ( EXISTS ( SELECT 1 FROM "+sTab+" Z WHERE Z."+type+"="+f+" AND Z.BDQXID='"+postId+"')";
            sql=sql+" OR (SELECT NVL(COUNT(1),0) \n" +
                    "  FROM "+sTab+" Z WHERE 1=1 AND Z.BDQXID='"+postId+"')=0";
            sql=sql+" OR ("+f+" IS NULL) )";

            return sql;
        }
        return " 1=1 ";
    }
}
